<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>JavaScript 表单验证</title>

    <script>
        /*校验输入框的信息是否符合我们需要的标准*/
        function validate(obj) {
            console.log(obj)
            var username = obj.value
            if (username.length < 12) {
                // 如果输入框的信息，不符合，则让err对应的dom元素显示出来
                document.getElementById("err").style.display = "inline";
            }
        }
    </script>
</head>
<body>
<!-- onblur 失去焦点 onfocs 获取焦点，就是鼠标离开或者进入 -->
<input type="text" name="username" id="username" onblur="validate(this)" />
<span style="color: red;display: none" id="err">用户名长度不合法</span>
</body>
</html>

<!-- ====================================== -->

<html>
<head>
    <script type="text/javascript">
        function validate_email(field, alerttxt) {
            with (field) {
                apos = value.indexOf("@")
                dotpos = value.lastIndexOf(".")
                if (apos < 1 || dotpos - apos < 2) {
                    alert(alerttxt);
                    return false
                }
                else {
                    return true
                }
            }
        }

        function validate_form(thisform) {
            with (thisform) {
                if (validate_email(email, "Not a valid e-mail address!") == false) {
                    email.focus();
                    return false
                }
            }
        }
    </script>
</head>

<body>
<form action="submitpage.htm" onsubmit="return validate_form(this);" method="post">
    Email: <input type="text" name="email" size="30">
    <input type="submit" value="Submit">
</form>
</body>

</html>